package com._system._g;

import java.io.File;
import java.net.URISyntaxException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.laymi.common._util.FileUtil;
import com.laymi.common._util.FreeMakerUtil;
import com.laymi.common._util.GID;
import com.laymi.common._util.JDataType;
import com.laymi.common._util.Underline2Camel;
import com.laymi.common._util.XKit;
import com.laymi.common.model.GTable;
import com.laymi.common.model.GTableColumn;
import com.laymi.common.model.Note;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.JMap;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

public class _GController extends Controller{
	
	static GTableService srv = GTableService.me;
	
	//项目路径
	private static final String projectPath = System.getProperty("user.dir");
	public void index() {
		render("/WEB-INF/_system/_g/table.html");
	}
	/**
	 * 加载首页Table
	 */
	public void list() {
		renderJson(srv.searchPage(getParaMap(), getParaToInt(0), getParaToInt(1)));
	}
	/**
	 * tr行删除
	 */
	public void delOne() {
		srv.delOne(getPara("id"));
		renderJson(Ret.ok("msg", "删除成功"));
	}
	/**
	 * 编辑页面
	 */
	public void edit() {
		GTable gTable = GTable.dao.findById(getPara(0));
		setAttr("gTable", gTable);
		render("/WEB-INF/_system/_g/edit.html");
	}

	/**
	 * 编辑按钮操作
	 */
	@Before(Tx.class)
	public void doedit() {
		GTable gt = getModel(GTable.class);
		GTable.dao.findById(gt.getId()).put(gt);
		gt.update();
		for (int i=0; i<getParaToInt(0); i++) {
			GTableColumn gtc=  getModel(GTableColumn.class, "gTableColumn[" + i + "]");
			GTableColumn.dao.findById(gtc.getId())
			.put(gtc)
			.update();
			gtc.update();
	    }
		renderJson(Ret.ok("msg", "更新成功"));
	}
	//跳转表单
	public void toStart() throws URISyntaxException {
		System.out.println(System.getProperty("user.dir"));
		render("/WEB-INF/_system/g.html");
	}
	//代码生成
	public void start() {
		String tableId = getPara("ids");
		//根据id查询表
		GTable gTable =GTable.dao.findById(tableId);
		String table_name = gTable.getTableName();
		String TableName = Underline2Camel.underline2Camel(table_name, false);
		String tableName = Underline2Camel.underline2Camel(table_name, true);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("TableName",TableName);
		map.put("tableName",tableName);
		map.put("table_name",table_name);
		map.put("tableComment",gTable.getGTableColumns());//全部
		map.put("tableCommentForm",gTable.getGTableColumnsForm());//表单全部字段
		map.put("tableCommentFormInline",gTable.getGTableColumnsFormInline());//表单行内
		map.put("tableCommentFormBlock",gTable.getGTableColumnsFormBlock());//表单行外
		map.put("tableCommentTable",gTable.getGTableColumnsTable());//table
		map.put("tableCommentQuery",gTable.getGTableColumnsQuery());//查询字段
		map.put("gTableColumns",gTable.getGTableColumns());//字段集合
		map.put("keyStrategy",gTable.getKeyStrategy());//主键策略
		map.put("version",gTable.getVersion());//版本号
		
		//Controller/Service路径
		System.out.println(projectPath);
		String javaPath = (projectPath+"/src/main/java/com/laymi/_admin/").replace("\\", "\\\\");
		String controllerPath = (projectPath+"/src/main/java/com/laymi/_admin/"+tableName+"/"+TableName+"Controller.java").replace("\\", "\\\\");
		String servicePath = (projectPath+"/src/main/java/com/laymi/_admin/"+tableName+"/"+TableName+"Service.java").replace("\\", "\\\\");
		String modelPath = (projectPath+"/src/main/java/com/laymi/_admin/"+tableName+"/"+TableName+".java").replace("\\", "\\\\");
		//_MappingKit路径
		String _MappingKitPath = (projectPath+"/src/main/java/com/laymi/common/model/_MappingKit.java.java").replace("\\", "\\\\");
		//Html路径
		String htmlPath =(projectPath+"/src/main/webapp/WEB-INF/_admin/").replace("\\", "\\\\");
		String tablePath =(projectPath+"/src/main/webapp/WEB-INF/_admin/"+tableName+"/table.html").replace("\\", "\\\\");
		String addPath =(projectPath+"/src/main/webapp/WEB-INF/_admin/"+tableName+"/add.html").replace("\\", "\\\\");
		String editPath =(projectPath+"/src/main/webapp/WEB-INF/_admin/"+tableName+"/edit.html").replace("\\", "\\\\");
		//路径处理
		File fileJava = new File(javaPath);
		FileUtil.judeDirExists(fileJava);
		File fileHtml = new File(htmlPath);
		FileUtil.judeDirExists(fileHtml);
		//模板引擎初始化
		FreeMakerUtil fm = new FreeMakerUtil();
		//获取生成的内容
		String c = "controller,service,table,add,edit";
		//String[] module = getParaValues("module");
		String[] module = c.split(",");
		for (int i = 0; i < module.length; i++) {
			if("controller".equals(module[i])){
				File controller = new File(controllerPath);
				FileUtil.judeDirExists(controller);
				fm.getTemplate("controller.ftl");
	    		fm.print("controller.ftl", map);
	    		fm.generateFile("controller.ftl", map, controllerPath);
			}else if("service".equals(module[i])){
				fm.getTemplate("service.ftl");
	    		fm.print("service.ftl", map);
	    		fm.generateFile("service.ftl", map, servicePath);
			}else if("table".equals(module[i])){
				File table = new File(tablePath);
				FileUtil.judeDirExists(table);
				fm.getTemplate("table.ftl");
	    		fm.print("table.ftl", map);
	    		fm.generateFile("table.ftl", map, tablePath);				
			}else if("add".equals(module[i])){
				fm.getTemplate("add.ftl");
	    		fm.print("add.ftl", map);
	    		fm.generateFile("add.ftl", map, addPath);				
			}else if("edit".equals(module[i])){
				fm.getTemplate("edit.ftl");
	    		fm.print("edit.ftl", map);
	    		fm.generateFile("edit.ftl", map, editPath);				
			}
		}
		renderJson(Ret.ok("msg", "代码生成完毕！"));
	}
	private static final String dataBaseName="laymi";
	private static final String sql1=
			"SELECT TABLE_NAME as tableName,TABLE_COMMENT as tableComment FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '"+dataBaseName+"'";
	private static final String sql2="select COLUMN_NAME as columnName,column_comment as columnComment,data_type as dataType  from INFORMATION_SCHEMA.Columns where table_name=? and table_schema='"+dataBaseName+"'";
	//同步数据库
		public void synDataBase() {
			//所有最新的更新添加完成的table放在这个集合，然后对比老的，进行设置类型
			  List<GTable> tablesx = new ArrayList<GTable>();
			//所有最新的更新添加完成的tableColumn放在这个集合，然后对比老的，进行删除
			  List<GTableColumn> columnsx = new ArrayList<GTableColumn>();
			//1：查询数据库所有表,排除系统表
			  List<Record> tableNames = Db.find(sql1);
			//2：根据上面的表名查询table表
			  for (Record record : tableNames) {
				  //百分比格式化
				  NumberFormat numberFormat = NumberFormat.getInstance();   
	 	          numberFormat.setMaximumFractionDigits(2);
	 	          //开始
				  String tableName = record.getStr("tableName");
				  String tableComment = record.getStr("tableComment");
				  GTable GtableOne = GTable.dao.findFirst(
						  "select * from g_table where tableName=?"
						  ,tableName);//根据表名查询table表
				  if(GtableOne!=null){//有则更新
					  GtableOne
					  //.setTableComment(record.getStr("tableComment"))表注释不更新了
					  .setVersion(GtableOne.getVersion()+1)
					  .update();
					  tablesx.add(GtableOne);
					  //有,查询字段集合
					  List<Record> columnNames = Db.find(sql2,tableName);
					  //根据id查询字段表集合
					  List<GTableColumn> columns = GTableColumn.dao.find(
							  "select * from g_table_column where tableId=?",GtableOne.getId());
					  for (Record record2 : columnNames) {
						  String columnName =record2.getStr("columnName");
						  String columnComment=record2.getStr("columnComment");
						  String dataType=record2.getStr("dataType");
						  int x = 1;
						  for (GTableColumn gTableColumn : columns) {
								if(columnName.equals(gTableColumn.getColumnName())){
									x=2;
									columnsx.add(gTableColumn);
									//这里没更新注释
									break;
								}
							}
						  if(x==1){//没有这个字段新增
							  String id = GID.getId();
			    	          String result = numberFormat.format((float)1/(float)columnNames.size()*100);
							  GTableColumn col=  new GTableColumn()
							  .setId(id)
							  .setTableId(GtableOne.getId())
							  .setCreateTime(new Date())
							  .setColumnComment(columnComment)
							  .setColumnName(columnName)
							  .setDataType(dataType)
							  .setJDataType(JDataType.getJDataTppe(dataType))
							  .setControlLength(result+"%")
							  .setDExtend("")
							  .setValidationRules("|");
							  if(col.getJDataType().equals("java.util.Date")){
								  col.setControlType("laytime");
							  }
							  if("longtext".equals(col.getDataType())){
								  col.setControlType("umeditor");
							  }
							   col.save();
							   columnsx.add(col);
						  }
					}
				  }else{//无则新增
					  String id = GID.getId();
					  GTable tab = new GTable()
					  .setId(id)
					  .setCreateTime(new Date())
					  .setTableName(tableName)
					  .setTableComment(tableComment);
					   tab.save();
					   tablesx.add(tab);
					   List<Record> columnNames2 = Db.find(sql2,tableName);
					   for (Record record2 : columnNames2) {
						    //新增表字段
						    String id2 = GID.getId();
						    GTableColumn col=  new GTableColumn();
						    col.setId(id2);
						    col.setTableId(id);
						    col.setCreateTime(new Date());
						    col.setColumnComment(record2.getStr("columnComment"));
						    col.setColumnName(record2.getStr("columnName"));
						    col.setDataType(record2.getStr("dataType"));
						    col.setJDataType(record2.getStr("jDataType"));
						    col.setControlLength(numberFormat.format((float)1/(float)columnNames2.size()*100)+"%");
						    col.setDExtend("")
						    .setValidationRules("|");
						    if("java.util.Date".equals(col.getJDataType())){
								  col.setControlType("laytime");
							  }
							  if("longtext".equals(col.getDataType())){
								  col.setControlType("umeditor");
							  } 
						    col.save();
							 columnsx.add(col);
					   }
				  }
			}
			  //查询所有table
			  List<GTable> ts = GTable.dao.find("select * from g_table");
			  for (GTable gTable : ts) {
				  int m = 1;
				  for (GTable gTable2 : tablesx) {
					  if(gTable.getId().equals(gTable2.getId())){
						  m=2;
					  }	
				  }
				  if(m==1){
					  gTable.delete();
				  }
			  }
			  //查询所有columns
			  List<GTableColumn> cs = GTableColumn.dao.find("select * from g_table_column");
			  for (GTableColumn gTableColumn : cs) {
				  int n = 1;
				  for (GTableColumn gTableColumn2 : columnsx) {
					  if(gTableColumn.getId().equals(gTableColumn2.getId())){
						  n=2;
					  }
				  }
				  if(n==1){
					  gTableColumn.delete();
				  }
			  }
			  renderJson(Ret.ok("msg", "数据库同步完毕！"));
		}
		/**
		 * 查询数据字典
		 */
		public void fD() {
			renderJson(XKit.getD(getPara("table"), getPara("text"), getPara("code"), getPara("extend")));
		}	
		/**
		 * 查询数据字典
		 */
		public void t() {
			render("/WEB-INF/_admin/blog/NewFile.html");
		}
		/**
		 * 查询数据字典
		 */
		public void t1() {
			render("/WEB-INF/_admin/blog/NewFile1.html");
		}
		/**
		 * 查询数据字典
		 */
		public void t2() {
			render("/WEB-INF/_admin/blog/NewFile2.html");
		}
}
